﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace Creventive.Wpf.ShellFactory.Utility
{
    /// <summary>
    /// Extensions of Linq
    /// </summary>
    public static class LinqExtensions
    {
        /// <summary>
        ///   Gets the index of the given item in the given collection, using the given comparer.
        /// </summary>
        /// <typeparam name = "T"></typeparam>
        /// <param name = "items">The items.</param>
        /// <param name = "item">The item.</param>
        /// <param name = "equalityComparer">The equality comparer.</param>
        /// <returns></returns>
        public static int IndexOf<T>(this IEnumerable<T> items, T item, IEqualityComparer<T> equalityComparer)
        {
            if (items is IList<T>)
            {
                var source = (IList<T>)items;
                for (int index = 0; index < source.Count; index++)
                {
                    if (equalityComparer.Equals(source[index], item))
                        return index;
                }
            }
            else if (items is IList)
            {
                var source = (IList)items;
                for (int index = 0; index < source.Count; index++)
                {
                    if (source[index] is T)
                    {
                        if (equalityComparer.Equals((T)source[index], item))
                            return index;
                    }
                }
            }
            else
            {
                int index = 0;
                foreach (var sourceItem in items)
                {
                    if (equalityComparer.Equals(sourceItem, item))
                        return index;
                    index++;
                }
            }

            return -1;
        }

        /// <summary>
        ///   Utility function to iterate the given list.
        /// </summary>
        /// <typeparam name = "T"></typeparam>
        /// <param name = "items">The items.</param>
        /// <param name = "action">The action.</param>
        public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
        {
            foreach (var item in items)
                action.Invoke(item);
        }

        /// <summary>
        /// Utility function to iterate the given list.
        /// </summary>
        /// <param name="items">The items.</param>
        /// <param name="action">The action.</param>
        public static void ForEach(this IEnumerable items, Action<object> action)
        {
            foreach (var item in items)
                action.Invoke(item);
        }
    }
}